<template>
  <div class="step2-container">
    <div class="title">
      Log in {{ institution.name }} Requesting initial credential inputs
    </div>

    <div class="form-container">
      <a-form
        :form="form"
        @submit="handleSubmit"
      >
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="Customer ID"
        >
          <a-input
            v-decorator="[
              'loginId',
              {
                initialValue: 'gavinBelson'
              },
              { rules: [{ required: true, message: 'Required' }] },
            ]"
            placeholder="Customer ID"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="Password"
        >
          <a-input
            v-decorator="[
              'password',
              {
                initialValue: 'hooli2016'
              },
              { rules: [{ required: true, message: 'Required' }] },
            ]"
            placeholder="Password"
          />
        </a-form-item>

        <div class="buttons-container">
          <a-button
            class="pre-button ant-btn-default"
            @click="$emit('prevStep')"
          >
            Change  Banks
          </a-button>
          <a-button
            type="primary"
            :loading="formLoading"
            @click="handleSubmit"
          >
            Submit
          </a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script>
import { changeBackStatus } from '@/api/flow/auth';
import { basiqConnections, getBasiqUser } from '@/api/risk/basiq';
import { mapState, mapGetters } from 'vuex';

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 }
};
const formTailLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 }
};

export default {
  data() {
    return {
      formItemLayout,
      formTailLayout,
      form: this.$form.createForm(this),

      formLoading: false
    };
  },

  computed: {
    ...mapState({
      hasMobile: (state) => !!state.user.info.mobile
    }),

    ...mapGetters(['currentUser'])
  },

  props: {
    institution: {
      type: Object,
      default: () => ({})
    }
  },

  methods: {
    // getBasiqUser
    getBasiqUser() {
      return new Promise((resolve, reject) => {
        const {
          email,
          mobile,
          first_name: firstName,
          last_name: lastName
        } = this.currentUser;
        const data = {
          email,
          mobile: `+61${mobile}`,
          firstName,
          lastName
        };

        if (!this.hasMobile) {
          resolve();
          return false;
        }
        getBasiqUser(data)
          .then(() => {
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // form validateFields
    validateFieldsForm() {
      const validateFieldsKey = [
        'loginId',
        'password'
      ];

      return new Promise((resolve, reject) => {
        const {
          form: { validateFieldsAndScroll }
        } = this;

        validateFieldsAndScroll(validateFieldsKey, { force: true, first: true }, (err, values) => {
          if (!err) {
            resolve(values);
            return false;
          }
          reject(false);
        });
      });
    },

    handleSubmit(e) {
      e.preventDefault();

      if (!this.hasMobile) {
        this.$notification.error({
          message: 'Please improve the mobile Phone Number information!',
          duration: 1
        });

        return;
      }

      this.formLoading = true;

      this.validateAndSubmit()
        .then(() => {
          changeBackStatus()
            .then(() => {
              this.$emit('succeeded');
            })
            .finally(() => {
              this.formLoading = false;
            });
        })
        .finally(() => {
          this.formLoading = false;
        });
    },

    validateAndSubmit() {
      return new Promise((resolve, reject) => {
        this.validateFieldsForm()
          .then(() => {
            this.$emit('success');
            this.submitForm()
              .then(async (data) => {
                console.log(data, 'dadada');
                // this.$emit('succeeded');
                resolve(data);
              })
              .catch((error) => {
                console.log('1212121', this);
                this.$emit('failed');
                reject(error);
              });
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // Retrieve password
    submitForm() {
      const validateFieldsKey = [
        'loginId',
        'password'
      ];

      return new Promise((resolve, reject) => {
        const fields = this.form.getFieldsValue(validateFieldsKey);
        const { id } = this.institution;

        this.getBasiqUser()
          .then(() => {
            basiqConnections({
              ...fields,
              institution: {
                id
              }
            })
              .then((data) => {
                resolve(data);
              })
              .catch((error) => {
                reject(error);
              });
          })
          .catch((error) => {
            reject(error);
          });
      });
    }

  }
};
</script>

<style lang="scss" scoped>
.step2-container {
  & > .title {
    text-align: center;
    font-size: $font-size-lg;
    font-weight: bold;
    margin-bottom: $margin-sm;
  }

  .form-container {
    max-width: 600px;
    margin: 0 auto;
    .buttons-container {
      display: flex;
      justify-content: flex-end;
      .pre-button {
        margin-right: $margin-xs;
      }
    }
  }
}
</style>
